package cn.kgc.controller;

import cn.kgc.entities.Emp;
import cn.kgc.pojo.Prop;
import cn.kgc.pojo.ResponseVO;
import cn.kgc.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Controller
public class EmpController {

    @Autowired
    private EmpService empService;

    @GetMapping("/emps/{pageNo}/{pageSize}")
    public String getAllEmp(@PathVariable("pageNo")Integer pageNo,
                            @PathVariable("pageSize") Integer pageSize,
                            Model model){
        List<Emp> list = empService.getAllEmp();
        model.addAttribute("list",list);
        return "empList";
    }

    @GetMapping("/emps/{id}")
    public String getEmpById(@PathVariable("id") Integer id,Model model){
        this.setProp(model);

        Emp emp = empService.getEmpById(id);
        model.addAttribute("emp",emp);
        return "emp";
    }

    @PostMapping("/emps")
    public String addEmp(Emp emp){
        empService.addEmp(emp);
        return "redirect:/emps";
    }

    @PutMapping("/emps")
    public String updateEmp(Emp emp){
        empService.updateEmp(emp);
        return "redirect:/emps";
    }

    @DeleteMapping("/emps/{id}")
    public String deleteEmpById(@PathVariable("id") Integer id){
        empService.deleteEmpById(id);
        return "redirect:/emps";
    }

    @GetMapping("/emps/view")
    public String toAddUI(Model model){
        this.setProp(model);
        model.addAttribute("emp",new Emp());
        return "emp";
    }

    private void setProp(Model model){
        List<Prop> sexs = new ArrayList<>();
        sexs.add(new Prop("M","男"));
        sexs.add(new Prop("F","女"));

        List<Prop> jobs = new ArrayList<>();
        jobs.add(new Prop("","请选择"));
        jobs.add(new Prop("1","助理工程师"));
        jobs.add(new Prop("2","初级工程师"));
        jobs.add(new Prop("3","高级工程师"));

        model.addAttribute("sexs",sexs);
        model.addAttribute("jobs",jobs);
    }

    @GetMapping("/emps/count/{name}")
    @ResponseBody
    public ResponseVO<Integer> countByName(@PathVariable("name")String name){
        Integer count = empService.countByName(name);
        ResponseVO<Integer> rs = new ResponseVO<Integer>();
        rs.setCode(20000);
        rs.setMsg("查询成功");
        rs.setData(count);
        return rs;
    }

}
